﻿/**
 * The AudioTrack Library by Chris J. Rock. Aug 10, 2011
 * Check out chrisjrock.net and be a king among men.
 *
 * Copyright (c) 2011 Chris J. Rock
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 **/


package net.chrisjrock.sound.audioTrack.mixer 
{
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import net.chrisjrock.sound.audioTrack.events.AudioTrackEvent;
	import net.chrisjrock.sound.audioTrack.track.IAudioTrack;
	import net.chrisjrock.sound.audioTrack.track.ISequencedTrack;
	
	/**
	 * Acts as a mixer to merge multiple tracks, even overlapping them if blending is desired.
	 * Because the child tracks are played linearly, this mixer also behaves as a sequenced track.
	 * @author Christopher J. Rock
	 */
	public class SequenceTrack extends AbstractMixer implements ISequencedTrack
	{
		private var _tracks:Vector.<ISequencedTrack> = new Vector.<ISequencedTrack>();
		
		private var _trackNum:int;
		private var _prevDurationSum:Number = 0;
		private var _currentTrack:ISequencedTrack;
		private var _nextTrack:ISequencedTrack;
		private var _nextTrackNum:int;
		private var _playing:Boolean;
		
		private var _duration:Number = 0;
		private var _loops:int;
		private var _loopInfinitely:Boolean;
		
		private var _overlapDuration:Number = 0;
		private var _overlapTimer:Timer;
		
		public function SequenceTrack (trackId:String)
		{
			super(trackId);
		}
		
		/**
		 * @inheritDoc
		 */		
		override public function dispose():void 
		{
			stop();
			
			if (_tracks)
			{
				var i:int = _tracks.length - 1;
				for (; i >= 0 ; i--)
				{
					removeTrack(_tracks[i]);
				}
				
				_tracks = null;
			}
			
			super.dispose();
		}
		
		/**
		 * @inheritDoc
		 */		
		override public function disposeAll ():void
		{
			stop();
			
			if (_tracks)
			{
				var trackNum:int = _tracks.length - 1;
				for (; trackNum >= 0 ; trackNum--)
				{
					if (_tracks[trackNum] is IAudioMixer)
					{
						IAudioMixer(_tracks[trackNum]).disposeAll();
					}
					else
					{
						_tracks[trackNum].dispose();
					}
				}
				_tracks = null;
			}
			
			super.dispose();
		}
		
		/**
		 * @inheritDoc
		 */		
		override public function addTrack (track:IAudioTrack):void 
		{
			if (track == null) 
			{
				throw (new Error("Cannot add a null value track. Attempted to add '" + track + "'."));
			}
			
			super.addTrack(track);
		}
		
		/**
		 * @inheritDoc
		 */		
		override public function hasTrack (track:IAudioTrack):Boolean
		{
			if (_tracks == null)
			{
				throw (new Error("Track list has been destroyed."));
			}
			
			if (!(track is ISequencedTrack))
			{
				return false;
			}
			
			return _tracks.indexOf(track) >= 0;
		}
		
		/**
		 * @inheritDoc
		 */		
		public function stop ():void 
		{
			if (_playing) 
			{
				_currentTrack.removeEventListener(AudioTrackEvent.AT_END , trackCompleteHandler);
				_currentTrack.stop();
				_playing = false;
				_trackNum = 0;
				_prevDurationSum = 0;
				if (_overlapTimer) 
				{
					_overlapTimer.removeEventListener(TimerEvent.TIMER , overlapTimerHandler);
					_overlapTimer.stop();
					_overlapTimer = null;
				}
				dispatchEvent(new AudioTrackEvent(AudioTrackEvent.STOP));
			}
		}
		
		/**
		 * @inheritDoc
		 */		
		public function play (restart:Boolean = false):void 
		{
			if (_tracks && _tracks.length && (restart || !_playing)) 
			{
				_playing = true;
				
				if (_currentTrack) 
				{
					if (_currentTrack.paused && !restart) 
					{
						_currentTrack.play();
						startOverlapTimer();
						dispatchEvent(new AudioTrackEvent(AudioTrackEvent.PLAY));
						return;
					}
					_currentTrack.stop();
					_currentTrack.removeEventListener(AudioTrackEvent.AT_END , trackCompleteHandler);
				}
				
				if (restart)
				{
					_trackNum = 0;
					_prevDurationSum = 0;
				}
				
				_currentTrack = _tracks[_trackNum];
				_currentTrack.addEventListener(AudioTrackEvent.AT_END , trackCompleteHandler);
				_currentTrack.play();
				startOverlapTimer();
				if (restart)
				{
					dispatchEvent(new AudioTrackEvent(AudioTrackEvent.AT_START));
				}
				dispatchEvent(new AudioTrackEvent(AudioTrackEvent.PLAY));
			}
		}
		
		/**
		 * Updates various data harvested from each subtrack.
		 * 
		 */		
		public function update ():void
		{
			_duration = 0;
			var trackNum:int;
			var tracksTotal:int = _tracks.length;
			for (; trackNum < tracksTotal ; trackNum++)
			{
				_duration += _tracks[trackNum].duration;
			}
		}
		
		/**
		 * @inheritDoc
		 */		
		public function pause():void 
		{
			if (!_playing) 
			{
				return;
			}
			
			_playing = false;
			_currentTrack.pause();
			if (_overlapTimer)
			{
				_overlapTimer.stop();
			}
			else if (_nextTrack && _nextTrack.playing)
			{
				_nextTrack.pause();
			}
			
			dispatchEvent(new AudioTrackEvent(AudioTrackEvent.PAUSE));
		}
		
		/**
		 * @inheritDoc
		 */		
		//TODO: Scrubbing doesn't work yet!
		//TODO: Scrubbing with overlap is not complete!
		public function scrubTo (position:Number):void 
		{
			/*var leaveStart:Boolean = this.position == 0;
			var leaveEnd:Boolean = this.position == _duration;
			
			if (_currentTrack)
			{
				_currentTrack.stop();
				_currentTrack.removeEventListener(AudioTrackEvent.AT_END , onTrackComplete);
				_currentTrack = null;
			}
			
			if (_overlapTimer)
			{
				_overlapTimer.removeEventListener(TimerEvent.TIMER , overlapTimerHandler);
				_overlapTimer.stop();
				_overlapTimer = null;
			}
			
			var trackPos:Number = position;
			var trackNum:int;
			var tracksTotal:int = _trackList.length;
			for (; trackNum < tracksTotal ; trackNum++)
			{
				if (trackPos >= _trackList[trackNum].duration)
				{
					trackPos -= _trackList[trackNum].duration;
					continue;
				}
				break;
			}
			
			_trackNum = trackNum;
			_currentTrack = _trackList[_trackNum];
			_currentTrack.pause();
			_currentTrack.scrubTo(trackPos);
			
			play();
			
			if (leaveStart)
			{
				dispatchEvent(new AudioTrackEvent(AudioTrackEvent.LEAVE_START));
			}
			else if (position == 0)
			{
				dispatchEvent(new AudioTrackEvent(AudioTrackEvent.AT_START));
			}
			if (leaveEnd)
			{
				dispatchEvent(new AudioTrackEvent(AudioTrackEvent.LEAVE_END));
			}
			else if (position == _duration)
			{
				dispatchEvent(new AudioTrackEvent(AudioTrackEvent.AT_END));
			}*/
		}
		
		override protected function addTrackToCollection(track:IAudioTrack):void
		{
			if (_tracks == null)
			{
				throw (new Error("Track list has been destroyed."));
			}
			
			_tracks.push(track);
			_duration += ISequencedTrack(track).duration;
		}
		
		override protected function removeTrackFromCollection (track:IAudioTrack):void
		{
			if (_tracks == null)
			{
				throw (new Error("Track list has been destroyed."));
			}
			
			var index:int = _tracks.indexOf(track);
			_tracks.splice(index , 1);
			_duration -= ISequencedTrack(track).duration; //TODO: Make sure you can't end up with a negative duration.
		}
		
		private function startOverlapTimer ():void 
		{
			if (_overlapDuration <= 0) 
			{
				return;
			}
			
			if (_overlapTimer)
			{
				_overlapTimer.start();
				return;
			}
			
			if (_nextTrack && _nextTrack.paused)
			{
				_nextTrack.play();
				return;
			}
			
			if (_tracks == null || _tracks.length <= 1) 
			{
				return;
			}
			
			_nextTrackNum = _trackNum + 1;
			if (_nextTrackNum >= _tracks.length && !_loopInfinitely && _loops <= 0) 
			{
				return;
			}
			
			if (_nextTrackNum >= _tracks.length)
			{
				_nextTrackNum = 0;
			}
			
			_nextTrack = _tracks[_nextTrackNum];
			
			if (_overlapDuration >= _currentTrack.duration || _overlapDuration >= _nextTrack.duration) 
			{
				return;
			}
			
			var overlapTimeRemaining:Number = _currentTrack.duration - _overlapDuration;
			if (!isNaN(_currentTrack.position))
			{
				overlapTimeRemaining -= _currentTrack.position;
			}
			
			if (overlapTimeRemaining > 0)
			{
				_overlapTimer = new Timer(overlapTimeRemaining);
				_overlapTimer.addEventListener(TimerEvent.TIMER , overlapTimerHandler);
				_overlapTimer.start();
			}
			else
			{
				//TODO: Finish this!
			}
		}
		
		private function overlapTimerHandler (event:TimerEvent):void 
		{
			_overlapTimer.removeEventListener(TimerEvent.TIMER , overlapTimerHandler);
			_overlapTimer.stop();
			_overlapTimer = null;
			
			_prevDurationSum += _currentTrack.duration - _overlapDuration;
			_currentTrack = _nextTrack;
			if (!_loopInfinitely && _nextTrackNum < _trackNum)
			{
				_loops--;
			}
			_trackNum = _nextTrackNum;
			_nextTrack = null;
			_playing = false;
			
			play();
		}
		
		private function trackCompleteHandler (event:Event):void 
		{
			event.target.removeEventListener(AudioTrackEvent.AT_END , trackCompleteHandler);
			if (event.target != _currentTrack) 
			{
				event.target.stop();
				return;
			}
			
			_prevDurationSum += _currentTrack.duration;
			_currentTrack.stop();
			_currentTrack = null;
			_playing = false;
			
			if (++_trackNum < _tracks.length || _loopInfinitely || _loops--) 
			{
				if (_trackNum >= _tracks.length)
				{
					_trackNum = 0;
					_prevDurationSum = 0;
				}
				play();
				return;
			}
			
			_loops = 0;
			_trackNum = 0;
			_prevDurationSum = 0;
			dispatchEvent(new AudioTrackEvent(AudioTrackEvent.AT_END));
		}
		
		/**
		 * @inheritDoc
		 */		
		public function get playing ():Boolean
		{
			return _playing;
		}
		
		/**
		 * How many times the track will be looped.
		 * @return 
		 * 
		 */		
		public function get loops ():int
		{
			return _loops;
		}
		
		/**
		 * @private
		 */		
		public function set loops (value:int):void 
		{
			if (_loops != value || _loopInfinitely) 
			{
				_loops = value;
				_loopInfinitely = false;
			}
		}
		
		/**
		 * Forces the track to loop infinitely. 
		 * @return 
		 * 
		 */		
		public function get loopInfinitely ():Boolean
		{
			return _loopInfinitely;
		}
		
		/**
		 * @private
		 */		
		public function set loopInfinitely (value:Boolean):void 
		{
			if (_loopInfinitely != value) 
			{
				_loopInfinitely = value;
				if (_loopInfinitely)
				{
					_loops = int.MAX_VALUE;
				}
			}
		}
		
		/**
		 * The duration at the end of each track that should overlap the next track.
		 */
		public function get overlapDuration():Number
		{
			return _overlapDuration;
		}
		
		/**
		 * @private
		 */		
		public function set overlapDuration(value:Number):void
		{
			_overlapDuration = value;
		}
		
		/**
		 * The number of the track currently being played.
		 * @return 
		 * 
		 */		
		public function get trackNum ():int
		{
			return _trackNum;
		}
		
		/**
		 * The number of tracks in the sequence. 
		 * @return 
		 * 
		 */		
		public function get trackCount ():int
		{
			return _tracks.length;
		}
		
		/**
		 * @inheritDoc
		 */	
		public function get position ():Number
		{
			if (!_currentTrack || isNaN(_currentTrack.position))
			{
				return NaN;
			}
			return _prevDurationSum + _currentTrack.position;
		}
		
		/**
		 * @inheritDoc
		 */		
		public function get duration ():Number
		{
			return _duration;
		}
		
		/**
		 * Returns the track currently being played. 
		 * @return 
		 * 
		 */	
		public function get currentTrack ():ISequencedTrack
		{
			return _currentTrack;
		}
		
		/**
		 * @inheritDoc
		 */		
		public function get paused ():Boolean
		{
			return !_playing && _currentTrack && _currentTrack.paused;
		}

	}
	
}